//
//  ReadLogView.swift
//  TLCLockDemo
//
//  Created by run on 2024/7/24.
//

import SwiftUI
import TLCLock

let yMdHmsFormatter: DateFormatter = {
    let f = DateFormatter()
    f.timeZone = TimeZone(abbreviation: "UTC+8")
    f.dateFormat = "yyyy-MM-dd HH:mm:ss"
    return f
}()

struct ReadLogView: View {


    let device: LockDevice

    @State var offset: String = "0"
    
    @State var logList: [TLCLock.LogModel] = []

    var body: some View {
        
        VStack {
            YxrInputView("offset", placeholderText: "日志起始index", text: $offset)
            
            List {
                ForEach(logList) { model in
                    VStack(alignment: .leading, spacing: 3.0) {
                        HStack {
                            Text("logId=\(model.logId)")
                                .font(.system(size: 12))
                            Spacer()
                            Text(model.logType.name)
                                .font(.system(size: 12))
                        }
                        Text("logType=\(model.logTypeValue)")
                            .font(.system(size: 12))
                        //                            HStack {
                        //                                Text("logType=\(model.logTypeValue)")
                        //                                    .font(.system(size: 12))
                        //                                Spacer()
                        //                                Text(model.logType.desc)
                        //                                    .font(.system(size: 12))
                        //                            }
                        Text("logTime=\(model.date, formatter: yMdHmsFormatter)")
                            .font(.system(size: 12))
                        
                        Text("info=\(model.otherInfo?.toString() ?? "{}")")
                            .font(.system(size: 12))
                    }
                }
            }
        }
        
        .yxrNavigationTitle("日志")
        .navigationBarItems(
            trailing: HStack {
                Button("读取日志") {
                    readLogs()
                }
            })
    }

    func readLogs() {
        logList.removeAll()
        guard let lockKey = Server.getSecret(device.macAddress) else {
            showToast("没有lockKey")
            return
        }

        let v = offset.trimmingCharacters(in: .whitespaces)
        guard let value = Int(v) else {
            showToast("请输入正确的数字")
            return
        }

        let offset = UInt32(value)

       lockTask(desc: "日志") {
            let result = await device.allLogList(from: offset, lockKey: lockKey)
            if result.isSuccess {
                let model = result.value!
                Log.info("total: \(result.value!)")
                
                DispatchQueue.main.async {
                    self.logList += model.logList
                }
            }

            return result
        }
    }
}

extension Dictionary where Key == String, Value: Any {
    func toString() -> String {
        let keyValuePairs = self.map { key, value in
            if let valueString = value as? String {
                return "\"\(key)\": \"\(valueString)\""
            } else if let valueInt = value as? Int {
                return "\"\(key)\": \(valueInt)"
            } else if let valueDouble = value as? Double {
                return "\"\(key)\": \(valueDouble)"
            } else if let valueBool = value as? Bool {
                return "\"\(key)\": \(valueBool ? "true" : "false")"
            } else {
                return "\"\(key)\": \(String(describing: value))"
            }
        }
        return "{\(keyValuePairs.joined(separator: ", "))}"
    }
}

extension LogType {
    var desc: String {
        switch self {
        case .power(let value):
            return "电量: \(value)"
        case .powerOn:
            return ""
        case .factoryReset:
            return ""
        case .dfu:
            return ""
        case .keyboardLocked:
            return ""
        case .cmdExec(let trackId, let cmdId, let cmdType):
            return "trackId: \(trackId) cmdId: \(cmdId) cmdType: \(cmdType.description)"
        case .onePwdOpen(let otp):
            return "一次性密码：\(otp ?? "无")"
        case .pwd(_, let pwdId, let type):
            return "type: \(type.description) pwdId: \(pwdId?.toString() ?? "无")"
        case .card(_, let cardId, let type):
            return "type: \(type.description) cardId: \(cardId?.toString() ?? "无")"
        case .pickLock:
            return ""
        case .finperprint(_, let fpId, let type):
            return "type: \(type.description) fpId: \(fpId?.toString() ?? "无")"
        case let .failed(type):
            return "解析失败\(type)"
        case .unknown:
            return "未知"
        }
    }
}

fileprivate extension UInt32 {
    func toString() -> String {
        return "\(self)"
    }
}
